package com.fire.eyes.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fire.core.base.controller.BaseController;
import com.fire.core.mode.TMitUserToken;
import com.fire.core.service.CkeckTokenService;
import com.fire.core.util.AjaxResult;
import com.fire.core.util.BlogUtil;
import com.fire.eyes.constants.ErrorCodeConstants;
import com.fire.eyes.model.*;
import com.fire.eyes.service.*;
import com.fire.eyes.validation.SiteFixDTO;
import com.fire.eyes.validation.SiteIdDTO;
import com.fire.eyes.validation.TokenDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.log4j.Logger;

import java.util.List;
import java.util.Map;

/**
 *
 * @ClassName: SiteController
 * @Description: 站点控制器
 * @author zhongzifeng
 * @date 2019/1/16 20:27
 *
 */
@Controller
public class SiteController extends BaseController {
	private final static Logger blogin = Logger.getLogger(SiteController.class);

	@Autowired
	private ISiteService iSiteService;
	@Autowired
	private CkeckTokenService ckeckTokenService;
	@Autowired
	private IUserAuthorityService iUserAuthorityService;
	@Autowired
	private IFireSupervisorUserService iFireSupervisorUserService;
	@Autowired
	private IFireMaintainUserService iFireMaintainUserService;
	@Autowired
	private IFireProprietorUserService iFireProprietorUserService;


	/**
	 * 查询消防站点列表
	 * 用于App向fire-app-server获得站点列表请求
	 * @author zhongzifeng
	 * @param tokenDTO 传入参数
	 * @param bindingResult 参数校验结果
	 * @return
	 */
	@PostMapping(value = "/sitelist")
	@ResponseBody
	public AjaxResult siteList(@RequestBody @Validated TokenDTO tokenDTO, BindingResult bindingResult) {
		blogin.info("EyesController.siteList获取到的消息参数" + tokenDTO.toString());
		BlogUtil.inlog(JSON.toJSONString(tokenDTO),"","/fire/eyes/sitelist","siteList","req");
		AjaxResult result;
		if (bindingResult.hasErrors()){
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				blogin.error("EyesController.siteList().error  错误为："+fieldError.getDefaultMessage());
				result = ajaxResult(ErrorCodeConstants.PARAM_WRONGFULL, fieldError.getDefaultMessage(), fieldError.getDefaultMessage());
				return result;
			}
			System.out.print("效验bu通过：）");
		}
		try {
			TMitUserToken token = ckeckTokenService.ckeckToken(tokenDTO.getToken());
			if(token == null){
				blogin.error("EyesController.siteList().error  错误为：无token记录");
				result = ajaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "无token记录", "无token记录");
				return result;
			}
			Integer userId = token.getUserid();
			Wrapper<UserAuthorityModel> userAutorityModel = new EntityWrapper<>();
			userAutorityModel.eq("userid",userId);
			UserAuthorityModel userAuthority = iUserAuthorityService.selectOne(userAutorityModel);
			String suthority = userAuthority.getAuthority();
			String column = "";
			String columnValue = "";
			// 业主单位
			String proprietor = "proprietor";
			if(proprietor.equals(suthority)){
				Wrapper<FireProprietorUserModel> fireProprietorUserWrapper = new EntityWrapper<>();
				fireProprietorUserWrapper.eq("userid",userId);
				FireProprietorUserModel fireProprietorUser = iFireProprietorUserService.selectOne(fireProprietorUserWrapper);
				column = "proprietor";
				columnValue = fireProprietorUser.getProprietor();
			}
			// 维保单位
			String maintainor = "maintainor";
			if(maintainor.equals(suthority)){
				Wrapper<FireMaintainUserModel> fireMaintainUserWrapper = new EntityWrapper<>();
				fireMaintainUserWrapper.eq("userid",userId);
				FireMaintainUserModel fireMaintainUser = iFireMaintainUserService.selectOne(fireMaintainUserWrapper);
				column = "maintainor";
				columnValue = fireMaintainUser.getMaintainor();
			}
			// 监管单位
			String supervisor = "supervisor";
			if(supervisor.equals(suthority)){
				Wrapper<FireSupervisorUserModel> fireSupervisorUserWrapper = new EntityWrapper<>();
				fireSupervisorUserWrapper.eq("userid",userId);
				FireSupervisorUserModel fireSupervisorUser = iFireSupervisorUserService.selectOne(fireSupervisorUserWrapper);
				column = "supervisorid";
				columnValue = fireSupervisorUser.getSupervisor();
			}
			Wrapper<SiteModel> siteWrapper = new EntityWrapper<>();
			siteWrapper.eq(column,columnValue);
			//List<SiteModel> siteList = iSiteService.selectList(siteWrapper);
			//Page<SiteModel> sitePage = iSiteService.selectPage(new Page<SiteModel>(siteListDTO.getPage(),siteListDTO.getPageSize()),siteWrapper);
			Page<Map<String, Object>> sitePage = iSiteService.querySiteList(new Page<Map<String, Object>>(tokenDTO.getPage(),tokenDTO.getPagesize()),column, columnValue);
			List siteList = sitePage.getRecords();
			result = ajaxResult(ErrorCodeConstants.SUCCESS, "操作成功",siteList, "操作成功");
			BlogUtil.inlog(JSON.toJSONString(result),"","/fire/eyes/sitelist","siteList","resp");
		} catch (Exception e){
			e.printStackTrace();
			blogin.error("EyesController.siteList().error  错误为：" + e);
			result = ajaxResult(ErrorCodeConstants.PARAM_WRONGFULL, "服务器开小差", "服务器开小差");
		}
		return result;
	}

	/**
	 * 查询消防站点详情
	 * 用于App向fire-app-server获得消防站点详情请求
	 * @author zhongzifeng
	 * @param siteIdDTO 传入参数
	 * @param bindingResult 参数校验结果
	 * @return
	 */
	@PostMapping(value = "/sitedetail")
	@ResponseBody
	public AjaxResult siteDetail(@RequestBody @Validated SiteIdDTO siteIdDTO, BindingResult bindingResult) {
		blogin.info("EyesController.siteDetail获取到的消息参数" + siteIdDTO.toString());
		BlogUtil.inlog(JSON.toJSONString(siteIdDTO),"","/fire/eyes/sitedetail","siteDetail","req");
		AjaxResult result;
		if (bindingResult.hasErrors()){
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				blogin.error("EyesController.siteDetail().error  错误为："+fieldError.getDefaultMessage());
				result = ajaxResult(ErrorCodeConstants.PARAM_WRONGFULL, fieldError.getDefaultMessage(), fieldError.getDefaultMessage());
				return result;
			}
			System.out.print("效验bu通过：）");
		}
		String siteId = siteIdDTO.getSiteid();
		Map site = iSiteService.querySiteDetail(siteId);
		result = ajaxResult(ErrorCodeConstants.SUCCESS, "操作成功",site, "操作成功");
		BlogUtil.inlog(JSON.toJSONString(result),"","/fire/eyes/sitedetail","siteDetail","resp");
		return result;
	}

	/**
	 * 站点信息校准
	 * @author zhongzifeng
	 * @param siteFixDTO 传入参数
	 * @param bindingResult 参数校验结果
	 * @return
	 */
	@PostMapping(value = "/sitefix")
	@ResponseBody
	public AjaxResult siteFix(@RequestBody @Validated SiteFixDTO siteFixDTO, BindingResult bindingResult) {
		blogin.info("EyesController.siteFix获取到的消息参数" + siteFixDTO.toString());
		BlogUtil.inlog(JSON.toJSONString(siteFixDTO),"","/fire/eyes/sitefix","siteFix","req");
		AjaxResult result;
		if (bindingResult.hasErrors()){
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				blogin.error("EyesController.siteFix().error  错误为："+fieldError.getDefaultMessage());
				result = ajaxResult(ErrorCodeConstants.PARAM_WRONGFULL, fieldError.getDefaultMessage(), fieldError.getDefaultMessage());
				return result;
			}
			System.out.print("效验bu通过：）");
		}
		// 更新smartThing更新建筑物
		iSiteService.siteFix(siteFixDTO);
		result = ajaxResult(ErrorCodeConstants.SUCCESS, "操作成功","", "操作成功");
		BlogUtil.inlog(JSON.toJSONString(result),"","/fire/eyes/sitefix","siteFix","resp");
		return result;
	}
}
